package service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthServiceProvider;
import net.oauth.server.OAuthServlet;
import net.oauth.signature.RSA_SHA1;
import tools.Util;

public class SaleService extends HttpServlet {

	private static final Logger logger = Logger.getLogger(SaleService.class.getName());

	private final static String CERTIFICATE =
		"-----BEGIN CERTIFICATE-----\n"
		+ "MIIDHDCCAoWgAwIBAgIJAMbTCksqLiWeMA0GCSqGSIb3DQEBBQUAMGgxCzAJBgNV\n"
		+ "BAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIG\n"
		+ "A1UEChMLR29vZ2xlIEluYy4xDjAMBgNVBAsTBU9ya3V0MQ4wDAYDVQQDEwVscnlh\n"
		+ "bjAeFw0wODAxMDgxOTE1MjdaFw0wOTAxMDcxOTE1MjdaMGgxCzAJBgNVBAYTAlVT\n"
		+ "MQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChML\n"
		+ "R29vZ2xlIEluYy4xDjAMBgNVBAsTBU9ya3V0MQ4wDAYDVQQDEwVscnlhbjCBnzAN\n"
		+ "BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAseBXZ4NDhm24nX3sJRiZJhvy9eDZX12G\n"
		+ "j4HWAMmhAcnm2iBgYpAigwhVHtOs+ZIUIdzQHvHeNd0ydc1Jg8e+C+Mlzo38OvaG\n"
		+ "D3qwvzJ0LNn7L80c0XVrvEALdD9zrO+0XSZpTK9PJrl2W59lZlJFUk3pV+jFR8NY\n"
		+ "eB/fto7AVtECAwEAAaOBzTCByjAdBgNVHQ4EFgQUv7TZGZaI+FifzjpTVjtPHSvb\n"
		+ "XqUwgZoGA1UdIwSBkjCBj4AUv7TZGZaI+FifzjpTVjtPHSvbXqWhbKRqMGgxCzAJ\n"
		+ "BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEU\n"
		+ "MBIGA1UEChMLR29vZ2xlIEluYy4xDjAMBgNVBAsTBU9ya3V0MQ4wDAYDVQQDEwVs\n"
		+ "cnlhboIJAMbTCksqLiWeMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEA\n"
		+ "CETnhlEnCJVDXoEtSSwUBLP/147sqiu9a4TNqchTHJObwTwDPUMaU6XIs2OTMmFu\n"
		+ "GeIYpkHXzTa9Q6IKlc7Bt2xkSeY3siRWCxvZekMxPvv7YTcnaVlZzHrVfAzqNsTG\n"
		+ "P3J//C0j+8JWg6G+zuo5k7pNRKDY76GxxHPYamdLfwk=\n"
		+ "-----END CERTIFICATE-----";

	/**
	 * Constructor of the object.
	 */
	public SaleService() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		String viewerid;
		String ownerid;
		String consumer_key;

		boolean signed = false;

		//TODO: implement sign fetch
		try {

			/**
			 * URL: http://oauthtest.s42.eatj.com/oauth/SignedFetchVerifyServlet
				Param Name-->oauth_consumer_key Value-->orkut.com
				Param Name-->oauth_nonce Value-->7fe2ce6b24e17c86
				Param Name-->opensocial_app_id Value-->10449685582340194994
				Param Name-->opensocial_viewer_id Value-->10972140642666904206
				Param Name-->oauth_timestamp Value-->1211519778
				Param Name-->opensocial_owner_id Value-->10972140642666904206
				Param Name-->oauth_signature Value-->eYwX2yWLpOZ+gb5oEFeIy+EM3j237nrj/1rj3yp69jgo/QaPk/OnXbXP9imEcERxtQLj9QqDD8cjbjMJ46VINc7bLab8qER1Xhkf4tTIkwfFXJW9tjQMBuGO8OVf9v0UAjAruWfSN331LLgGFecKQR5UTD0qAAyzTnFY9aSmqg8=
				Param Name-->xoauth_signature_publickey Value-->pub.1199819524.-1556113204990931254.cer
				Param Name-->oauth_token Value-->
				Param Name-->oauth_signature_method Value-->RSA-SHA1
			 */
			OAuthServiceProvider provider =
				new OAuthServiceProvider(null, null, null);
			OAuthConsumer consumer =
				new OAuthConsumer(null, "orkut.com", null, provider);
			consumer.setProperty(RSA_SHA1.X509_CERTIFICATE, CERTIFICATE);
			OAuthMessage message = OAuthServlet.getMessage(request, null);

			OAuthAccessor accessor = new OAuthAccessor(consumer);
			viewerid = message.getParameter("opensocial_viewer_id");
			ownerid = message.getParameter("opensocial_owner_id");
			consumer_key = message.getParameter("oauth_consumer_key");
			message.validateSignature(accessor);
			signed = true;
//			out.print("REQUEST STATUS::OK");
//			out.print("<br>");
//			} catch (OAuthProblemException ope) {
//			System.out.println(OAuthServlet.htmlEncode(ope.getProblem()));

		} catch (Exception e) {
			e.printStackTrace();
			viewerid = request.getParameter("viewerid");
			ownerid = request.getParameter("ownerid");
			//TODO:consumerkey should combine with id
			consumer_key = "custom";
		}

		viewerid = Util.convertToGlobal(consumer_key, viewerid);
		ownerid = Util.convertToGlobal(consumer_key, ownerid);

		String output="";
		String path = request.getPathInfo();
		try{
			String[] token = path.split("/");
			String action = token[1];
			if(action.equals("get")){
				String id = viewerid;
				String name = request.getParameter("name");
				String thumbnail = request.getParameter("thumbnail");
				output = FriendSale.getData(id,name,thumbnail,"");
			}else if(action.equals("buy")){
				String masterid = viewerid;
				String slaveid = request.getParameter("slaveid");
				slaveid = Util.convertToGlobal(consumer_key, slaveid);
				String nickname = request.getParameter("nick");
				nickname = java.net.URLDecoder.decode(nickname,"UTF-8");
				output = FriendSale.buy(masterid,slaveid,nickname);
			}else if(action.equals("dostuff")){
				String masterid = viewerid;
				String slaveid = request.getParameter("slaveid");
				slaveid = Util.convertToGlobal(consumer_key, slaveid);
				String stuffid = request.getParameter("stuffid");
				output = FriendSale.dostuff(masterid, slaveid, stuffid);
			}else{
				request.setAttribute("viewerid", viewerid);
				request.setAttribute("ownerid", ownerid);
				if(request.getParameter("slaveid")!=null){
					request.setAttribute("slaveid", Util.convertToGlobal(consumer_key, request.getParameter("slaveid")));
				}
				request.setAttribute("domain", consumer_key);
				request.getRequestDispatcher("../"+action+".jsp").forward(request, response);
			}
		}catch(Exception e){
			output = e.getMessage();
		}
		PrintWriter out = response.getWriter();
		out.print(output);
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		doGet(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
